package com.whf.android.jar.view.font;

import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.whf.android.jar.R;
import com.whf.android.jar.util.storage.LattePreference;

/**
 * 仿微信字体大小调整
 *
 * @author qf
 * @version 1.0
 */
public class FontView extends RelativeLayout implements FontSizeView.OnChangeCallbackListener {

    private final static String DEFAULT_POSITION = "14f";
    protected final Context mContext;
    private final TextView textName, textValue;
    private final float textSize = 16f;

    public FontView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        final int defaultPosition = LattePreference.getAppInt(DEFAULT_POSITION, 1);
        try {
            LayoutInflater.from(context).inflate(R.layout.hai_view_font_size, this, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        textName = findViewById(R.id.font_text_name);
        textValue = findViewById(R.id.font_text_value);
        FontSizeView sizeView = findViewById(R.id.font_fsv);
        if (sizeView != null) {
            //滑动返回监听
            sizeView.setChangeCallbackListener(this);
            sizeView.setDefaultPosition(defaultPosition);
        }
        setTextSize(textSize + 2 * (defaultPosition - 1));
    }

    public final void setTextSize(float size) {
        if (textName != null) {
            textName.setTextSize(TypedValue.COMPLEX_UNIT_PX, sp2px(size));
        }
        if (textValue != null) {
            textValue.setTextSize(TypedValue.COMPLEX_UNIT_PX, sp2px(size));
        }
    }

    protected int sp2px(float sp) {
        final float scale = this.mContext.getResources().getDisplayMetrics().scaledDensity;
        return (int) (sp * scale + 0.5f);
    }

    @Override
    public void onChangeListener(int position) {
        LattePreference.setAppInt(DEFAULT_POSITION, position);
        int s = position - 1;
        setTextSize(textSize + 2 * s);
    }
}
